package com.yvon.maple.cloud.web.data;

import com.google.common.collect.Lists;
import com.yvon.boot.mybatis.IBaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

@Slf4j
public abstract class AbstractController<E, D, V, S extends IBaseService<E>> extends ApiController {

    protected AbstractController() {
    }

    @Autowired
    private S baseService;



    protected E voToEntity(V vo) {
        E entity = null;
        if (null != vo) {
            try {
                entity = this.getEntityClass().newInstance();
                BeanUtils.copyProperties(vo, entity);
            } catch (Exception var4) {
                log.error(var4.getMessage());
            }
        }

        return entity;
    }

    protected D entityToDto(E entity) {
        D dto = null;
        if (null != entity) {
            try {
                dto = this.getDtoClass().newInstance();
                BeanUtils.copyProperties(entity, dto);
            } catch (Exception var4) {
                log.error(var4.getMessage());
            }
        }

        return dto;
    }

    protected List<E> voToEntity(List<V> voList) {
        List<E> entityList = Lists.newLinkedList();
        if (!voList.isEmpty() && voList.size() > 0) {
            voList.forEach((v) -> {
                E entity = this.voToEntity(v);
                entityList.add(entity);
            });
        }

        return entityList;
    }

    protected List<D> entityToDto(List<E> entityList) {
        List<D> dtoList = Lists.newLinkedList();
        if (null != entityList && entityList.size() > 0) {
            entityList.forEach((e) -> {
                D dto = this.entityToDto(e);
                dtoList.add(dto);
            });
        }

        return dtoList;
    }

    protected Class<E> getEntityClass() {
        ParameterizedType parameterizedType = (ParameterizedType)this.getClass().getGenericSuperclass();
        Type entityType = parameterizedType.getActualTypeArguments()[0];
        return (Class)entityType;
    }

    protected Class<D> getDtoClass() {
        ParameterizedType parameterizedType = (ParameterizedType)this.getClass().getGenericSuperclass();
        Type dtoType = parameterizedType.getActualTypeArguments()[1];
        return (Class)dtoType;
    }

    protected S getService() {
        return this.baseService;
    }
}
